package com.efounder.push;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.BeforeLoginCheckUtils;
import com.huawei.android.hms.agent.R;
import com.utilcode.util.AppUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 1、PushMessageReceiver 是个抽象类，该类继承了 BroadcastReceiver。<br/>
 * 2、需要将自定义的 XiaoMiMessageReceiver 注册在 AndroidManifest.xml 文件中：
 * <pre>
 * {@code
 *  <receiver
 *      android:name="com.xiaomi.mipushdemo.XiaoMiMessageReceiver"
 *      android:exported="true">
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" />
 *      </intent-filter>
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" />
 *      </intent-filter>
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.ERROR" />
 *      </intent-filter>
 *  </receiver>
 *  }</pre>
 * 3、XiaoMiMessageReceiver 的 onReceivePassThroughMessage 方法用来接收服务器向客户端发送的透传消息。<br/>
 * 4、XiaoMiMessageReceiver 的 onNotificationMessageClicked 方法用来接收服务器向客户端发送的通知消息，
 * 这个回调方法会在用户手动点击通知后触发。<br/>
 * 5、XiaoMiMessageReceiver 的 onNotificationMessageArrived 方法用来接收服务器向客户端发送的通知消息，
 * 这个回调方法是在通知消息到达客户端时触发。另外应用在前台时不弹出通知的通知消息到达客户端也会触发这个回调函数。<br/>
 * 6、XiaoMiMessageReceiver 的 onCommandResult 方法用来接收客户端向服务器发送命令后的响应结果。<br/>
 * 7、XiaoMiMessageReceiver 的 onReceiveRegisterResult 方法用来接收客户端向服务器发送注册命令后的响应结果。<br/>
 * 8、以上这些方法运行在非 UI 线程中。
 *
 * @author mayixiang
 */
public class XiaoMiMessageReceiver extends PushMessageReceiver {
    private static final String TAG = "XiaoMiMessageReceiver";

    private String mRegId;
    private String mTopic;
    private String mAlias;
    private String mAccount;
    private String mStartTime;
    private String mEndTime;

    @Override
    public void onReceivePassThroughMessage(Context context, MiPushMessage message) {
        LogUtils.i("onReceivePassThroughMessage:" + message.toString());
        String log = context.getString(R.string.recv_passthrough_message, message.getContent());

        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        }


    }

    @Override
    public void onNotificationMessageClicked(Context context, MiPushMessage message) {
        LogUtils.i("onNotificationMessageClicked:" + message.toString());
        try {

            //1.跳转首页

            if (!BeforeLoginCheckUtils.checkHasIMUserAccount() || !BeforeLoginCheckUtils.checkProfileisFull()) {
                //没有登录或者没有资源文件 打开应用首页
                AppUtils.launchApp(AppUtils.getAppPackageName());
                return;
            }
            Class clazz = Class.forName(context.getResources().getString(R.string.from_group_backto_first));

            Intent intent = new Intent(context, clazz);
            //context是service 或者广播的，启动activity必须使用FLAG_ACTIVITY_NEW_TASK
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            //intent.toUri(Intent.URI_INTENT_SCHEME);
            //intent:#Intent;launchFlags=0x10000000;component=com.efounder.ospopenplanet/com.pansoft.openplanet.activity.TabBottomActivityForTalkChain;S.a=1123;end
            //2.清除小米推送的角标
            PushManager pushManager = new PushManager(context);
            pushManager.clearPushNotification();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onNotificationMessageArrived(Context context, MiPushMessage message) {

        LogUtils.i("onNotificationMessageArrived:" + message.toString());
//        String log = context.getString(R.string.arrive_notification_message, message.getContent());
//
        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        }
        LogUtils.i(mTopic, mAlias);
    }

    @Override
    public void onCommandResult(Context context, MiPushCommandMessage message) {
        LogUtils.i("onCommandResult:" + message.toString());
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
        String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
        String log;
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
                log = context.getString(R.string.register_success);
            } else {
                log = context.getString(R.string.register_fail);
            }
        } else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAlias = cmdArg1;
                log = context.getString(R.string.set_alias_success, mAlias);
            } else {
                log = context.getString(R.string.set_alias_fail, message.getReason());
            }
        } else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAlias = cmdArg1;
                log = context.getString(R.string.unset_alias_success, mAlias);
            } else {
                log = context.getString(R.string.unset_alias_fail, message.getReason());
            }
        } else if (MiPushClient.COMMAND_SET_ACCOUNT.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAccount = cmdArg1;
                log = context.getString(R.string.set_account_success, mAccount);
            } else {
                log = context.getString(R.string.set_account_fail, message.getReason());
            }
        } else if (MiPushClient.COMMAND_UNSET_ACCOUNT.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAccount = cmdArg1;
                log = context.getString(R.string.unset_account_success, mAccount);
            } else {
                log = context.getString(R.string.unset_account_fail, message.getReason());
            }
        } else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mTopic = cmdArg1;
                log = context.getString(R.string.subscribe_topic_success, mTopic);
            } else {
                log = context.getString(R.string.subscribe_topic_fail, message.getReason());
            }
        } else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mTopic = cmdArg1;
                log = context.getString(R.string.unsubscribe_topic_success, mTopic);
            } else {
                log = context.getString(R.string.unsubscribe_topic_fail, message.getReason());
            }
        } else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mStartTime = cmdArg1;
                mEndTime = cmdArg2;
                log = context.getString(R.string.set_accept_time_success, mStartTime, mEndTime);
            } else {
                log = context.getString(R.string.set_accept_time_fail, message.getReason());
            }
        } else {
            log = message.getReason();
        }
        LogUtils.i(log, mRegId, mAlias, mAccount, mTopic, mStartTime, mEndTime);
    }

    @Override
    public void onReceiveRegisterResult(Context context, MiPushCommandMessage message) {
        // onReceiveRegisterResult:command={register},
        // resultCode={0}, reason={null}, category={null},
        // commandArguments={[JtufrpSq/XbvfBXiX45Xy0zsQufk1wV3OLCUAxvjvKhQVU1Vbf/Dh+ldELgWBk0A]}
        LogUtils.i("onReceiveRegisterResult:" + message.toString());
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);

        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
                //保存小米push 需要的 regid
                EnvironmentVariable.setProperty("pushToken", mRegId);
                LogUtils.i("mRegId:" + mRegId);
                try {
                    //Class className = Class.forName("com.efounder.chat.event.PushTokenEvent");
                    Object object = ReflectUtils.reflect("com.efounder.chat.event.PushTokenEvent").newInstance(mRegId).get();
                    EventBus.getDefault().postSticky(object);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

}
